<template>
  <div>
    <van-search @input="onInput" v-model="value" shape="round" />
    <div v-if="!MusicList.length" class="hotSearch">
      <p>热门搜索</p>
      <div class="hotSearchItem">
        <span
          @click="onClickSearch(item.first)"
          v-for="(item, index) in hotSearch"
          :key="index"
          >{{ item.first }}</span
        >
      </div>
    </div>
    <div v-else class="MusicItem">
      <p>最佳匹配</p>
      <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <SongList
        v-for="(item, index) in MusicList"
        :key="index"
        :artists="item.ar[0].name"
        :name="item.name"
      />
    </van-list>
    </div>

  </div>
</template>

<script>
import SongList from '@/components/SongList.vue'
import { getHotSearch, getHotSearchMusic } from '@/api/hotSearch'
export default {
  name: 'Search',
  data () {
    return {
      value: '',
      hotSearch: [],
      MusicList: [],
      loading: false,
      finished: false,
      page: 1
    }
  },

  // 组件注册
  components: {
    SongList
  },

  // 获取到数据和方法
  created () {
    this.getSearchItem()
  },
  // 定义方法
  methods: {
    async getSearchItem () {
      const res = await getHotSearch()
      this.hotSearch = res.data.result.hots
    },
    async onClickSearch (value) {
      this.value = value
      const res = await getHotSearchMusic({
        keywords: this.value,
        limit: 10
      })
      this.MusicList = res.data.result.songs
    },
    onInput () {
      clearTimeout(this.timeId)
      this.finished = false
      this.page = 1
      if (!this.value) {
        this.MusicList = []
      } else {
        this.timeId = setTimeout(async () => {
          const res = await getHotSearchMusic({
            keywords: this.value,
            limit: 10
          })
          this.MusicList = res.data.result.songs
        }, 800)
      }
    },
    async onLoad () {
      this.page++
      const res = await getHotSearchMusic({
        keywords: this.value,
        limit: 10,
        offset: (this.page - 1) * 10
      })
      console.log(res.data)
      if (res.data.result.songs) {
        this.MusicList.push(...res.data.result.songs)
        this.loading = false
      } else {
        this.finished = true
      }
    }
  }
}
</script>

<style scoped lang="less">
.hotSearch {
  p {
    padding: 0 10px;
    font-size: 14px;
    color: #999;
  }
  span {
    display: inline-block;
    border: 1px solid #ccc;
    border-radius: 15px;
    padding: 7px 12px;
    font-size: 12px;
    margin: 5px;
  }
}
.MusicItem {
  p {
    padding: 0 10px;
    font-size: 14px;
    color: #999;
  }
}
</style>
